package com.xiaotao.learn.thread.concurrent.cas.simple;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

public class CASHandler extends UnsafeHandler {
    private final static Unsafe UNSAFE;
    private final static long OFFSET;

    static {
        try {
            UNSAFE = getUnsafe();
            OFFSET = UNSAFE.objectFieldOffset(NumberClass.class.getDeclaredField("value"));
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new Error(e);
        }
    }

    @Override
    public void increase() {
        long t = value;
        while (!UNSAFE.compareAndSwapLong(this, OFFSET, t, t + 1)) {
            t = value;
        }
    }

    @Override
    public void decrease() {
        long t = value;
        while (!UNSAFE.compareAndSwapLong(this, OFFSET, t, t - 1)) {
            t = value;
        }
    }

    @Override
    public long getValue() {
        return super.getValue();
    }

    private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
        Field field = Unsafe.class.getDeclaredField("theUnsafe");
        field.setAccessible(true);
        return (Unsafe)field.get(Unsafe.class);
    }


}
